<template>
  <div class="box">
    <!-- 分析报告下载 -->
    <div class="panel">
      <h5><i class="circle"></i><span>分析报告下载</span></h5>
      <template v-if="analysisReport.length > 0">
        <el-table :data="analysisReport" class="eltable">
          <el-table-column type="index" label="序号" width="60">
          </el-table-column>
          <!-- <el-table-column prop="keyword" label="下载内容"> </el-table-column> -->
          <el-table-column prop="name" label="报告名称"> </el-table-column>
          <!-- <el-table-column prop="_taskType" label="报告类型"> </el-table-column> -->
          <el-table-column prop="format" label="格式">
            <template>
              <p>docx</p>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="_startTime" label="时间"> </el-table-column> -->
          <el-table-column prop="createtime" label="创建时间">
          </el-table-column>
          <el-table-column prop="finishtime" label="完成时间">
          </el-table-column>
          <!-- <el-table-column prop="percent" label="进度">
            <template slot-scope="scope">
              <el-progress
                :stroke-width="6"
                :color="scope.row.color"
                :percentage="scope.row.percent"
                class="elprogress"
              ></el-progress>
            </template>
          </el-table-column> -->
          <el-table-column prop="percent" label="进度">
            <template slot-scope="scope">
              <el-progress
                v-if="parseInt(scope.row.state) == 100"
                :stroke-width="8"
                status="success"
                :percentage="parseInt(scope.row.state)"
                class="elprogress"
              ></el-progress>
              <el-progress
                v-else
                :stroke-width="8"
                :percentage="parseInt(scope.row.state)"
                class="elprogress"
              ></el-progress>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" width="180px">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleDownload(scope.row)"
                >下载</el-button
              >
              <el-button size="small" @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
          <!-- <el-table-column prop="" label="操作" width="180px">
            <template slot-scope="scope">
              <div class="tools">
                <p>
                  <span @click="downloadReport('analysis', scope)">下载</span
                  ><i></i>
                </p>
                <p><span @click="handleDelReport(scope)">删除</span><i></i></p>
              </div>
            </template>
          </el-table-column> -->
        </el-table>
        <el-pagination
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="ipi"
          :page-size="ips"
          :total="total"
          class="elpagination"
        ></el-pagination>
      </template>
      <!-- no-data -->
      <div v-else class="no-data">
        <loading1 :emptyText="analysisReportEmptyText" />
      </div>
    </div>
    <!-- 期刊报告下载 -->
    <div class="panel">
      <h5>
        <i class="circle"></i><span>期刊报告下载</span>
        <p class="more" @click="toMorePage">查看全部&nbsp;></p>
      </h5>
      <template v-if="journalReport.length > 0">
        <div class="swiper-box">
          <swiper
            navigation
            :pagination="{ clickable: true }"
            :options="journalSwiperOptions"
          >
            <swiper-slide
              v-for="(item, index) in journalReport"
              :key="index"
              class="swiper-item-box"
            >
              <div class="logo" @click="toPage(item)">
                <img :src="item.src" alt="" />
              </div>
              <p class="info" @click="toPage(item)">
                <span>{{ item.title }}</span>
                <span>(共{{ item.issue }}期)</span>
              </p>
              <!-- <h6></h6>
              <p>(共{{item.issue}}期)</p> -->
            </swiper-slide>
          </swiper>
          <div class="swiper-button swiper-button-prev"></div>
          <div class="swiper-button swiper-button-next"></div>
        </div>
      </template>
      <!-- no-data -->
      <div v-else class="no-data">
        <loading1 :emptyText="journalReportEmptyText" />
      </div>
    </div>
    <!-- 内部报告下载 -->
    <div class="panel">
      <h5><i class="circle"></i><span>内部报告下载</span></h5>
      <template v-if="contentReport.length > 0">
        <div class="swiper-box">
          <swiper
            navigation
            :pagination="{ clickable: true }"
            :options="contentSwiperOptions"
          >
            <swiper-slide
              v-for="(item, index) in contentReport"
              :key="index"
              class="swiper-item-box"
            >
              <div class="logo" @click="toPage2(item)">
                <img :src="item.src" alt="" />
              </div>
              <p class="info" @click="toPage2(item)">
                <span>{{ item.title }}</span>
              </p>
            </swiper-slide>
          </swiper>
          <div class="swiper-button swiper-button-prev"></div>
          <div class="swiper-button swiper-button-next"></div>
        </div>
      </template>
      <!-- no-data -->
      <div v-else class="no-data">
        <loading1 :emptyText="contentReportEmptyText" />
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
// swiper
import "swiper/components/navigation/navigation.scss";
import "swiper/components/pagination/pagination.scss";
import "swiper/components/scrollbar/scrollbar.scss";
import { Swiper, SwiperSlide } from "vue-awesome-swiper";
import SwiperCore, {
  Navigation,
  Pagination,
  Scrollbar,
  Autoplay,
  A11y,
} from "swiper";
SwiperCore.use([Navigation, Pagination, Scrollbar, Autoplay, A11y]);
export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  data() {
    return {
      // 分析报告下载
      arOri: [],
      analysisReport: [],
      analysisReportEmptyText: "loading",
      ipi: 1,
      ips: 5,
      total: 0,
      analysisReportInterval: null,
      // 期刊报告下载
      journalReport: [],
      journalReportEmptyText: "loading",
      journalSwiperOptions: {
        slidesPerView: "auto",
        freeMode: true,
        spaceBetween: 20,
        pagination: {
          el: ".swiper-pagination",
        },
        navigation: {
          // 左右两边的箭头 也要引入Navigation
          nextEl: ".swiper-button-next", // 左右按钮的class类名
          prevEl: ".swiper-button-prev",
        },
        autoplay: false, // 自动播放
        delay: 4000, // 自动播放间隔
      },
      // 内部报告下载
      contentReport: [],
      contentReportEmptyText: "loading",
      contentSwiperOptions: {
        slidesPerView: "auto",
        freeMode: true,
        spaceBetween: 20,
        pagination: {
          el: ".swiper-pagination",
        },
        navigation: {
          // 左右两边的箭头 也要引入Navigation
          nextEl: ".swiper-button-next", // 左右按钮的class类名
          prevEl: ".swiper-button-prev",
        },
        autoplay: false, // 自动播放
        delay: 4000, // 自动播放间隔
      },
    };
  },
  methods: {
    init() {
      // this.getAnalysisReport();
      // this.analysisReportInterval = setInterval(this.getAnalysisReport, 6000);
      // 分析报告
      this.getAnalysisList();
      this.analysisReportInterval = setInterval(this.getAnalysisList, 10000);
      // 期刊报告
      this.getJournalReport();
      // 内部报告
      this.getContentReport();
    },
    // 分析报告
    // getAnalysisReport() {
    //   this.analysisReportEmptyText = "loading";
    //   this.$get(this.$Url.report.analysisReports, {
    //     ipi: this.ipi,
    //     ips: this.ips,
    //   })
    //     .then((res) => {
    //       let data = res.data || { list: [] };
    //       // console.log("data", data);
    //       if (data.list.length <= 0) {
    //         this.analysisReportEmptyText = "暂无数据";
    //         this.analysisReport = [];
    //         return;
    //       }
    //       data.list.forEach((v) => {
    //         v._taskType = v.taskType == 1 ? "科技分析报告" : "-";
    //         v._startTime = moment(v.startTime).format("YYYY-MM-DD HH:mm:ss");
    //         v.color = v.percent == 100 ? "#67c23a" : "#2f41c8";
    //       });
    //       this.analysisReport = data.list;
    //       this.total = data.total;
    //       if (
    //         (this.total === 0 && this.analysisReportInterval !== null) ||
    //         data.list.filter((v) => v.percent != 100).length <= 0
    //       ) {
    //         clearInterval(this.analysisReportInterval);
    //       }
    //     })
    //     .catch((err) => {
    //       if (this.analysisReportInterval !== null) {
    //         clearInterval(this.analysisReportInterval);
    //       }
    //     });
    // },
    getAnalysisList() {
      this.analysisReportEmptyText = "loading";
      this.$post(this.$Url.center.reports)
        .then((res) => {
          let data = res.data || [];
          if (data.length > 0) {
            this.total = data.length;
            this.arOri = JSON.parse(JSON.stringify(data));
            this.analysisReport = data.slice(
              this.ips * (this.ipi - 1),
              this.ips * this.ipi
            );
          } else {
            this.arOri = [];
            this.analysisReport = [];
            this.total = 0;
            this.analysisReportEmptyText = "暂无分析报告！";
          }
        })
        .catch((err) => {
          this.analysisReportEmptyText = "暂无分析报告！";
        });
    },
    // 报告下载
    handleDownload(item) {
      if (parseInt(item.state) !== 100) {
        this.$message({
          type: "warning",
          duration: 1000,
          message: "报告生成中",
        });
        return;
      }
      this.$getBlob(this.$Url.center.reportDownload, {
        id: item.id,
      })
        .then((res) => {
          let filename =
            res.headers["content-disposition"].split(";")[1].split("=")[1] ||
            "";
          if (filename !== "") {
            if (
              !(
                filename.endsWith(".doc") ||
                filename.endsWith(".docx") ||
                filename.endsWith(".xls") ||
                filename.endsWith(".pdf")
              )
            ) {
              filename += ".pdf";
            }
          }
          let blob = new Blob([res.data]);
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, decodeURI(filename));
          } else {
            let a = document.createElement("a");
            a.download = decodeURI(filename);
            a.href = window.URL.createObjectURL(blob);
            a.click();
          }
        })
        .catch((err) => {});
    },
    // 删除报告
    handleDelete(item) {
      this.$confirm("是否删除当前报告", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$get(this.$Url.center.reportDel, {
            id: item.id,
          })
            .then((res) => {
              if (res.status === 200) {
                this.getAnalysisList();
                this.$message({
                  type: "success",
                  message: "删除成功！",
                });
              }
            })
            .catch((err) => {});
        })
        .catch((err) => {
          this.$message({
            type: "error",
            message: res.data,
          });
        });
    },
    handleCurrentChange(val) {
      this.ipi = val;
      if (Math.ceil(this.arOri.length / this.ips) < this.ipi) {
        this.ipi = 1;
      }
      this.analysisReport = this.arOri.slice(
        this.ips * (this.ipi - 1),
        this.ips * this.ipi
      );
      // if (this.analysisReportInterval !== null) {
      //   clearInterval(this.analysisReportInterval);
      // }
      // this.getAnalysisList();
      // this.analysisReportInterval = setInterval(this.getAnalysisList, 6000);
      // this.getAnalysisReport();
      // this.analysisReportInterval = setInterval(this.getAnalysisReport, 6000);
    },
    // 期刊报告
    getJournalReport() {
      this.$post(this.$Url.report.periodicalReportAll, {
        ipi: 1,
        ips: 10,
        types: "期刊报告",
      })
        .then((res) => {
          let ths = this;
          let data = res.data.data || [];
          if (data.length > 0) {
            let journalReport = [];
            data.forEach((v) => {
              if (v.source.length > 0) {
                journalReport.push({
                  title: v.source[0] && v.source[0].key,
                  issue: v.total,
                  src: require("@/assets/img/report/u3712.png"),
                  content: v.result || [],
                });
              }
            });
            this.journalReport = journalReport;
            // console.log("journalReport", journalReport);
            this.journalReport.forEach((v) => {
              let imageUrlArr = v.content.filter((v) => v.image_url);
              // console.log("v:", v);
              // console.log("imageUrlArr:", imageUrlArr);
              if (imageUrlArr.length > 0) {
                this.getImageUrl(imageUrlArr[0].image_url, (d) => {
                  ths.$set(v, "src", d);
                });
              } else {
                // ths.$set(v, "src", require("@/assets/img/report/u3712.png"));
              }
            });
            if (journalReport.length <= 0) {
              this.journalReportEmptyText = "暂无期刊报告！";
            }
          } else {
            this.journalReportEmptyText = "暂无期刊报告！";
          }
        })
        .catch((err) => {});
    },
    // 内部报告
    getContentReport() {
      this.$post(this.$Url.report.periodicalReport, {
        ipi: 1,
        ips: 10,
        types: "内部报告",
      })
        .then((res) => {
          let result = res.data.result || [];
          if (result.length > 0) {
            let contentReport = [];
            result.forEach((v) => {
              contentReport.push({
                title: v.name,
                src: require("@/assets/img/report/u3712.png"),
                image_url: v.image_url,
                esId: v.esId,
              });
            });
            this.contentReport = contentReport;
            let ths = this;
            this.contentReport.forEach((v) => {
              // if (v.src === "") {
              ths.getImageUrl(v.image_url, (d) => {
                ths.$set(v, "src", d);
              });
              // }
            });
            if (contentReport.length <= 0) {
              this.contentReportEmptyText = "暂无内部报告！";
            }
          } else {
            this.contentReportEmptyText = "暂无内部报告！";
          }
        })
        .catch((err) => {});
    },
    // 封面回显
    getImageUrl(image_url, func) {
      if (image_url.indexOf(".") > -1) {
        this.$axios({
          method: "get",
          url: this.$Url.report.download2,
          params: {
            filename: image_url,
            bucketName: "gdt-bucket",
          },
          responseType: "blob",
        }).then((res) => {
          // console.log("res", res.data.size);
          if (res.data.size) {
            let blob = new Blob([res.data]);
            let url = window.URL.createObjectURL(blob);
            func && func(url);
          }
        });
      }
    },
    toMorePage() {
      let obj = {
        page: "all",
        source: "全部",
        year: "全部",
      };
      let url = this.$router.resolve({
        name: "reportJournal",
        params: {
          id: encodeURIComponent(JSON.stringify(obj)),
        },
      });
      window.open(url.href, "_blank");
    },
    toPage(item) {
      let obj = {
        page: "item",
        source: item.title,
        year: "全部",
      };
      let url = this.$router.resolve({
        name: "reportJournal",
        params: {
          id: encodeURIComponent(JSON.stringify(obj)),
        },
      });
      window.open(url.href, "_blank");
    },
    // 内部报告详情页
    toPage2(item) {
      let obj = {
        esId: item.esId,
      };
      let url = this.$router.resolve({
        name: "reportContentDetail",
        params: {
          id: encodeURIComponent(JSON.stringify(obj)),
        },
      });
      window.open(url.href, "_blank");
    },
    // 报告下载
    // downloadReport(type, scope) {
    //   if (type === "analysis") {
    //     let percent = scope.row.percent;
    //     if (percent != 100) {
    //       this.$alert("报告生成中，请耐心等待。", "提示", {
    //         confirmButtonText: "确定",
    //         callback: (action) => {},
    //       });
    //     } else {
    //       axios
    //         .get(`${this.$Url.report.analysisReportDownload}/${scope.row.id}`, {
    //           responseType: "blob",
    //         })
    //         .then((res) => {
    //           let filename =
    //             res.headers["content-disposition"]
    //               .split(";")[1]
    //               .split("=")[1] || "";
    //           if (filename) {
    //             filename = decodeURI(filename);
    //           }
    //           const aLink = document.createElement("a");
    //           aLink.style.display = "none";
    //           aLink.href = window.URL.createObjectURL(res.data);
    //           aLink.setAttribute("download", filename);
    //           document.body.appendChild(aLink);
    //           aLink.click();
    //           aLink.remove();
    //         })
    //         .catch((err) => {});
    //     }
    //   }
    // },
    // 删除
    // handleDelReport(scope) {
    //   this.$confirm("是否删除该报告?", "删除", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(() => {
    //       this.$post(`${this.$Url.report.analysisReportDelete}/${scope.row.id}`)
    //         .then((res) => {
    //           if (res.status === 200) {
    //             this.$message({
    //               type: "success",
    //               message: "删除成功!",
    //             });
    //             if (this.analysisReportInterval !== null) {
    //               clearInterval(this.analysisReportInterval);
    //             }
    //             this.getAnalysisReport();
    //             this.analysisReportInterval = setInterval(
    //               this.getAnalysisReport,
    //               6000
    //             );
    //           } else {
    //             this.$message({
    //               type: "error",
    //               message: data.data,
    //             });
    //           }
    //         })
    //         .catch((err) => {});
    //     })
    //     .catch(() => {});
    // },
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    if (this.analysisReportInterval !== null) {
      clearInterval(this.analysisReportInterval);
    }
  },
};
</script>

<style lang="scss" scoped>
.el-button--primary {
    color: #FFF;
    background-color: $mainColor !important;
    border-color: $mainColor !important;
}
.el-button--primary:active,.el-button--primary:focus,.el-button--primary:hover{
  color: #FFF !important;
    background-color: $mainColor !important;
    border-color: $mainColor !important;
}
.el-button:focus, .el-button:hover {
    color: $mainColor;
    border-color: $mainColor;
    background-color: $hoverColor;
}
.box {
  position: relative;
  padding: 0.2rem;
  .panel {
    position: relative;
    width: 100%;
    padding: 0 0.26rem;
    border-radius: 8px;
    margin-bottom: 0.18rem;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    text-align: center;
    background-color: $color2;
    h5 {
      position: relative;
      width: 100%;
      padding: 0.14rem 0.09rem;
      border-bottom: 1px solid $color36;
      box-sizing: border-box;
      font-size: 0.16rem;
      font-weight: normal;
      text-align: left;
      color: $color47;
      .circle {
        position: relative;
        width: 0.16rem;
        height: 0.1rem;
        margin-right: 0.18rem;
        vertical-align: middle;
        &:before {
          position: absolute;
          top: 50%;
          left: -0.04rem;
          z-index: 1;
          width: 0.1rem;
          height: 0.1rem;
          border-radius: 50%;
          margin-top: -0.04rem;
          background-color: $color48;
          content: "";
        }
        &:after {
          position: absolute;
          top: 50%;
          right: 0;
          z-index: 1;
          width: 0.1rem;
          height: 0.1rem;
          border-radius: 50%;
          margin-top: -0.04rem;
          background-color: $mainColor;
          content: "";
        }
      }
      span {
        vertical-align: middle;
      }
      .more {
        position: absolute;
        top: 0.18rem;
        right: 0.09rem;
        font-size: 0.14rem;
        color: $color116;
        cursor: pointer;
        &:hover {
          color: $color47;
        }
      }
    }
    .eltable {
      width: 100%;
      .elprogress {
        // min-width: 180px;
        width: 85%;
        ::v-deep {
          .el-progress__text {
            font-size: 0.12rem !important;
          }
        }
      }
      .tools {
        display: flex;
        align-items: center;
        p {
          margin-right: 0.2rem;
          cursor: pointer;
        }
      }
    }
    .elpagination {
      padding: 0.2rem 0;
      text-align: right;
    }
    .swiper-box {
      position: relative;
      padding: 0.2rem 0;
      .swiper-item-box {
        width: 2rem;
        margin-left: 0.2rem !important;
        cursor: pointer;
        &:hover {
          .info {
            text-decoration: underline;
            color: $mainColor;
          }
        }
        .logo {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 1.63rem;
          margin-bottom: 0.1rem;
          img {
            max-width: 1.31rem;
            max-height: 100%;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
          }
        }
        .info {
          width: 100%;
          font-size: 0.15rem;
          font-weight: normal;
          span {
            display: block;
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
    .swiper-button {
      top: 50%;
      width: 0.42rem;
      height: 0.42rem;
      line-height: 0.42rem;
      margin-top: -0.42rem;
      &:after {
        font-size: 0.2rem;
        color: $mainColor;
      }
      &.swiper-button-prev {
        left: -0.21rem;
      }
      &.swiper-button-next {
        right: -0.21rem;
      }
    }
  }
}
.no-data {
  min-height: 1.5rem;
  line-height: 1.5rem;
}
</style>
